import user from '@/api/user'
import { getToken, setToken, removeToken, getMenus, setMenus, removeMenus, getAvatar, setAvatar, removeAvatar, getUnitOptions, setUnitOptions, removeUnitOptions } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: getAvatar(),
  menus: getMenus(),
  unitOptions: getUnitOptions()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_UintOptions: (state, unitOptions) => {
    state.unitOptions = unitOptions
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      user.login({ username: username, password: password }).then(response => {
        const { data } = response
        if (!data.token) reject('无效用户，请联系管理员。')
        const unitIds = data.unitId.split(',')
        const unitName = data.unitName.split(',')
        const unitOptions = unitIds.map((v, i) => {
          return {
            id: +v,
            name: unitName[i]
          }
        })
        commit('SET_TOKEN', data.token)
        commit('SET_AVATAR', data.profilePhoto)
        commit('SET_MENUS', data.menu)
        commit('SET_UintOptions', unitOptions)
        setToken(data.token)
        setAvatar(data.profilePhoto)
        setMenus(data.menu)
        setUnitOptions(unitOptions)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      user.logout(state.token).then(async() => {
        commit('permission/SET_ROUTES', [], { root: true })
        await dispatch('resetToken')
        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录重置数据
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_MENUS', '')
      commit('SET_NAME', '')
      commit('SET_UintOptions', '')
      removeToken()
      removeMenus()
      removeAvatar()
      removeUnitOptions()
      resetRouter()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

